var myChirp = (function () {

    // Establish arrays, contact object var, and url
    var profileObj = [];
    var friendsObj = [];
    var chirpsObj = [];
    var userbase = [];
    var firebases = [];
    var urlLoc = [];
    var profileEdit;
    var friendToAdd;
    var baseUrl = '.firebaseio.com/';
    //var friends = 'friends';
    //var chirps = 'chirps';

    /* --------------------baseUrl attached to individual friend firebases-------------------------------------*/

    /* ----------------------------------------------URL Maker-------------------------------------------------*/

    function urlMakerPoster(target, key) {
        if (!key) {                  // does key exist? If the key doesn't exist (falsy), then return line 16. Else, return line 18.
            return "https://" + firebases[0] + baseUrl + target + "/.json";
        } else {
            return "https://" + firebases[0] + baseUrl + target + "/" + key + "/.json";
        }
        }
        // falsy values
        //
        // false
        // 0
        // null
        // undefined
        // NaN
        // "" (empty string)

        // truthy value
        // Everything that is not falsy in JS
    
    function urlMakerGetter(target, key) {
        if (!key) {                  // does key exist? If the key doesn't exist (falsy), then return line 16. Else, return line 18.
            for (var i = 0; i <= firebases.length + 1; i++) {
                var fbUrl = "https://" + firebases[i] + baseUrl + target + "/.json";
                masterXhr('GET', fbUrl, null, showChirpContent, genericErrorCallback);
            }
        } else {
            for (var i = 0; i <= firebases.length + 1; i++) {
                return "https://" + firebases[i] + baseUrl + target + "/" + key + "/.json";
            }
        }
    }
    // Master CRUD callout
    function masterXhr(verb, url, data, callback_success, callback_error, extra) {
        var request = new XMLHttpRequest();
        request.open(verb, url, true);
        request.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                if (callback_success && typeof (callback_success) == "function") {
                    callback_success(JSON.parse(this.response));
                    console.log(this.response);
                }
            } else {
                if (callback_error && typeof (callback_error) == "function") {
                    callback_error("MASTER XHR ERROR: " + this.response);
                }
            }
        };
        if (data) {                          // check on VERB type (GET or POST)
            request.send(JSON.stringify(data))
        } else {
            request.send();
        }
    }
    // Username constructor
    function Friend(name, handler, city, url) {
        this.name = name;
        this.handler = handler;
        this.city = city;
        this.url = url;
        this.chirp = [];
    };

    // Chirp constructor
    function Chirp(subject, message, username) {
        this.subject = subject;
        this.message = message;
        this.date = moment();
        this.username = username;
    };

    // Profile constructor
    function Profile(name, handle, city) {
        this.name = name;
        this.handle = handle;
        this.city = city;
    }
    function editProfile(tempId) {

        //create temporary object of profile in array (based on index argument)
        var profileEdit = tempId;
        var tProfile = profileObj[tempId];

        $('#profileName').val(tProfile.name);
        $('#profileFirebase').val(tProfile.handle);
        $('#profileCity').val(tProfile.city);
        $('#myModal').modal("show");
    }

    function editSave() {
        var name = $('#profileName').val();
        var handle = $('#profileFirebase').val();
        var city = $('#profileCity').val();

        console.log(name, handle, city);
        var objToPost = {
            "name": name,
            "handle": handle,
            "city": city
        }
        console.log(objToPost);
        profileObj.splice(0, 1);
        profileObj.push(objToPost);
        firebases[0] = handle;
        console.log(profileObj);
        console.log(firebases[0]);
        console.log(firebases);
        $('#profile-name').html("");
        $('#profile-firebase').html("");
        $('#profile-city').html("");
        $('#profile-name').append('<a ="#"><i class="glyphicon glyphicon-user"></i>' + name + '</a>');
        $('#profile-firebase').append('<a ="#"><i class="glyphicon glyphicon-user"></i>' + handle + '</a>')
        $('#profile-city').append('<a ="#"><i class="glyphicon glyphicon-home"></i>' + city + '</a>')
    }

    function addBirdie() {
        var name = $('#friendInput').val();
        var handle = $('#friendFireInput').val();

        console.log(name, handle);
        var objToPost = {
            "name": name,
            "handle": handle,
        }

        friendsObj.push(objToPost);
        firebases.push(handle);

        renderBirdieBuddies();
    }

    function renderBirdieBuddies() {
        var tBrd;
        var tStr = "";
        var tRes = $('#birdBuddyRender');
        tRes.empty();

        var counter = 0;
        var birdieObj;
        for (var i in friendsObj) {
            var birdie = friendsObj[i];

            // action buttons
            var deleteBtn = '<button onclick="myChirp.doDelete(' + counter + ')" type="button" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>'

            //render to the screen
            tStr = "";
            tStr += "<tr>";
            tStr += "<td>" + birdie.name + "</td>";
            tStr += "<td>" + birdie.handle + "</td>";
            tStr += "<td>" + deleteBtn + "</td>"
            tStr += "</tr>"
            counter++;
            tRes.append(tStr);
        }
    }

    function killBirdie(cId) {
        friendsObj.slice(cId, 1);
        renderBirdieBuddies();
    }

    // POST Chirp functions
    function postChirp() {
        var subject = $('#subject').val();
        var chirp = $('#chirpArea').val();
        var username = $('#profileName').val();
        console.log(subject, chirp);
        var objToPost = {
            "subject": subject,
            "message": chirp,
            "username": username,
            "date": moment()
        }

        masterXhr('POST', urlMakerPoster("chirps"), objToPost);
        console.log(urlMakerPoster());
        $('#subject').val("");
        $('#chirpArea').val("");
        getChirps();
    }

    //GET Chirp functions
    function getChirps() {
        urlMakerGetter('chirps');
        //masterXhr('GET', urlMakerOther("chirps"), null, showChirpContent, genericErrorCallback);
    }

    function showChirpContent(tData) {
        //chirpsObj = [];         // clear stored chirps
        var counter = 0;
        var chirpObj;
        for (var i in tData) {
            var chirp = tData[i];
            chirpObj = new Chirp(chirp.username, chirp.subject, chirp.message, chirp.date, i);
            chirpsObj.push(chirpObj);
            renderChirpsToScreen();
        }
    }

    function renderChirpsToScreen() {
        var tCrp;
        var tStr = "";
        var tRes = $('#chirpsRender');
        tRes.empty();

        var counter = 0;
        var chirpObj;
        for (var i in chirpsObj) {
            var chirp = chirpsObj[i];

            //render to the screen
            tStr = "";
            tStr += "<tr>";
            tStr += "<td>" + chirp.username + "</td>";
            tStr += "<td>" + chirp.subject + "</td>";
            tStr += "<td>" + chirp.message + "</td>";
            tStr += "<td>" + chirp.date + "</td>";
            tStr += "</tr>"
            counter++;
            tRes.append(tStr);
        }
    }

    function genericErrorCallback(msg) {
        alert(msg);
    }

    var doStuff = function () {
        chirpsObj = [];
        getChirps();
    };
    setInterval(doStuff, 10000);
    

    //function chirpRefresh() {
    //    setInterval(function () {
    //    $.getJSON(urlMaker(), function (chirps) {
    //        $("ul").append('<li>' + value.chirps + '<li>');
    //    })
    //},5000)
    //}
    //chirpRefresh();
    return {
        doPost: postChirp,
        doGet: getChirps,
        doEdit: editProfile,
        doEditSave: editSave,
        doBirdie: addBirdie,
        doDelete: killBirdie
    }

})();